/*
 * cmdinterpreter.cpp
 *
 *  Created on: 2021年12月10日
 *      Author: t1019
 */

#include "cmdinterpreter.h"

namespace bt_cmdinterpreter {
CmdInterpreter::CmdInterpreter(const s_CmdNode* p)
{
	root = p;
	current = p;
	for(int i = 0;i<=max_length;i++)
		buffer[i] = 0;
	group = 0;
	quit = 0;
	back = 0;
}

void CmdInterpreter::handler(char e)
{
	if(!e)
		return;
	if(e == quit)	//TODO 判断是否为退格 是否为返回
	{
		_back_root();
		_clear_buffer();
	}
	else
	{
		_append_event(e);
		current = current->node;
		while(current)
		{
			if((current->event<128 && e == current->event)
					||(current->event >= 128 && _is_ingroup(e,current->event)))
			{
				current->func(buffer);	//进入 执行函数
				break;
			}
			else
				current = current->next;
		}
		if(!current)
		{	//全不匹配回根节点
			_back_root();
			_clear_buffer();
		}
		else if(!current->node)
		{	//当前节点为终止点回根节点
			current = root;
			_clear_buffer();
		}
	}
}

bool CmdInterpreter::_is_ingroup(char e,unsigned char event)
{
	if(!group)
		return false;
	const s_CmdGroup* p;
	for(p = group;p->event != event;p++);
	const char* ch = p->group;
	while(*ch)
	{
		if(*ch == e)
			return true;
		else
			ch++;
	}
	return false;
}

void CmdInterpreter::_back_root()
{
	current = root;
	root->func(buffer);
}

bool CmdInterpreter::_append_event(char e)
{
	for(int i = 0;i<max_length;i++)
	{
		if(buffer[i] == 0)
		{
			buffer[i] = e;
			buffer[i+1] = 0;
			return false;
		}
		else if(i == max_length - 1)
		{
			_clear_buffer();
			return true;
		}
	}
	return false;
}

void CmdInterpreter::setQuit(const char ch)
{
	quit = ch;
}

void CmdInterpreter::setBack(const char ch)
{
	back = ch;
}

void CmdInterpreter::_clear_buffer()
{
	for(int i = 0;i<=max_length;i++)
		buffer[i] = 0;
}

void CmdInterpreter::setGroups(const s_CmdGroup* gr)
{
	group = gr;
}

CmdInterpreter::~CmdInterpreter()
{
	// TODO Auto-generated destructor stub
}

} /* namespace bt_cmdinterpreter */
